//
//  LinkList.cpp
//  LinkListDemo
//
//  Created by 李禹 on 15/5/26.
//  Copyright (c) 2015年 dayu. All rights reserved.
//

#include "LinkList.h"

void InitList(LinkList &L) {
    L = (LinkList)malloc(sizeof(LNode));    //产生头结点，并使L指向头结点
    if (!L) {   //存储分配失败
        exit(OVERFLOW);
    }
    L->next = NULL;     //头结点指针域为NULL
}

void DestroyList(LinkList &L) {     //改变L
    LinkList q;
    while (L) {
        q = L->next;
        free(L);
        L = q;
    }
}

void ClearList(LinkList L) {    //不改变L
    LinkList p = L->next;
    L->next = NULL;
    DestroyList(p);
}

Status ListEmpty(LinkList &L) {
    if (L->next) {
        return false;
    }else {
        return true;
    }
}

int ListLength(LinkList L) {
    int length = 0;
    LinkList q = L->next;
    while (q) {
        length++;
        q = q->next;
    }
    return length;
}

Status GetElem(LinkList L, int i, ElemType &e) {
    int j = 1;
    LinkList q = L->next;
    while (q && j<i) {
        j++;
        q = q->next;
    }
    if (!q || j>i) {
        return ERROR;
    }
    e = q->data;
    return OK;
}

int LoctionElem(LinkList L, ElemType e, Status(* compare)(ElemType, ElemType)) {
    int i = 0;
    LinkList q = L->next;
    while (q ) {
        i++;
        if (compare(q->data, e)) {
            return i;
        }
        q = q->next;
    }
    return 0;
}

Status ProiorElem(LinkList L, ElemType cur_e, ElemType &pre_e) {
    LinkList q, p = L->next;
    while (p->next) {
        q = p->next;
        if (q->data == cur_e) {
            pre_e = p->data;
            return OK;
        }
        p = q;
    }
    return ERROR;
}

Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e) {
    LinkList p = L->next;
    while (p->next) {
        if (p->data  == cur_e) {
            next_e = p->next->data;
            return OK;
        }
        p = p->next;
    }
    return ERROR;
}

Status ListInsert(LinkList L, int i, ElemType e) {
    int j = 0;
    LinkList s, p = L;
    while (p && j < i-1) {
        j++;
        p = p->next;
    }
    if (!p || j>i-1) {
        return ERROR;
    }
    s = (LinkList)malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}

Status ListDelete(LinkList L, int i, ElemType &e) {
    int j = 0;
    LinkList q, p = L;
    while (p->next && j < i-1) {
        j++;
        p = p->next;
    }
    if (!p || j > i-1) {
        return ERROR;
    }
    q = p->next;
    p->next = q->next;
    e = q->data;
    free(q);
    return OK;
}

void ReveserList(LinkList L) {
    LinkList p = L->next;
    LinkList s;
    while (p && p->next) {
        s = p->next->next;
        p->next->next = L->next;
        L->next = p->next;
        p->next = s;
    }
}

void ListTraverse(LinkList L, void(* visit)(ElemType &)) {
    LinkList p = L->next;
    while (p) {
        visit(p->data);
        p = p->next;
    }
    printf("\n");
}
